package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Resource
    private IFollowService followService;
    @Resource
    private IBlogService blogService;

    /**
     * 根据博客id查询博客详情，同时为用户字段赋值
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        //根据博客id查询博客
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("用户不存在。");
        }
        Long userId = blog.getUserId();//发布者用户id
        //根据用户id查询用户
        User user = userService.getById(userId);
        //用户字段赋值，以便前端展示
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        //查询blog是否被当前用户点赞过(大拇指是否高亮)
        blog.setIsLike(isBlogLiked(blog));
        return Result.ok(blog);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            //查询blog是否被当前用户点赞过(大拇指是否高亮)
            blog.setIsLike(isBlogLiked(blog));
        });
        return Result.ok(records);
    }

    /**
     * 判断博客是否被当前用户点赞过
     * @param blog
     * @return
     */
    private Boolean isBlogLiked(Blog blog) {
        //判断当前用户是否点赞过
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null) {
            //用户未登录，无法查询自己是否点赞过
            return null;
        }
        Long userId = userDTO.getId();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score = redisTemplate.opsForZSet().score(key, userId.toString());//注意isMember第二个参数是Object类型
        Boolean alreadyLiked = (score != null);
        return alreadyLiked;
    }

    /**
     * 用户点赞/取消点赞，同一个用户最多点赞一次，再点赞就是取消
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //判断当前用户是否点赞过
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //如果查不到score，说明用户id不在zset中，反之，在zset中
        Double score = redisTemplate.opsForZSet().score(key, userId.toString());//注意isMember第二个参数是Object类型
        boolean alreadyLiked = (score != null);
        //未点赞过，数据库点赞数+1，同时保存用户到redis集合，表示点赞过了
        if (!alreadyLiked) {
            boolean updateSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (updateSuccess) {
                //根据时间戳排序，以便获取点赞时间最早的五个用户
                redisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //已经点赞过，数据库点赞数-1，同时将用户从redis集合移除，表示没点赞过
            boolean updateSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (updateSuccess) {
                redisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询为id博客点赞的用户(点赞时间top5最早的用户)
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        //查询top5点赞用户 zrange key 0 4
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5UserIds = redisTemplate.opsForZSet().range(key, 0, 4);
        if (top5UserIds == null || top5UserIds.isEmpty()) {
            return Result.ok(new ArrayList<UserDTO>());
        }
        //解析用户id, 根据用户id查询用户
        ArrayList<UserDTO> userDTOs = new ArrayList<>();
        for (String userIdStr : top5UserIds) {
            Long userId = Long.parseLong(userIdStr);
            User user = userService.getById(userId);
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
            userDTOs.add(userDTO);
        }
        return Result.ok(userDTOs);
    }

    /**
     * 将blog保存到数据库，同时推送给自己的所有粉丝
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        if (blog.getShopId() == null) {
            return Result.fail("必须指定店铺!");
        }
        // 保存探店博文
        boolean saveSuccess = save(blog);
        if (!saveSuccess) {
            return Result.fail("探店博文保存失败！");
        }
        // 获取当前用户的所有粉丝id(关注当前用户的人的id)
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 推送blog在数据库的id给所有粉丝的收件箱。粉丝收件箱：以粉丝id作为key的zset，分数为时间戳
        for (Follow follow : follows) {
            Long userId = follow.getUserId();//粉丝id
            String key = RedisConstants.FEED_KEY + userId;
            redisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 滚动查询我收到的博主(我关注的博主)的blog
     * @param max 本次查询的最大时间戳(zset得分) 第一次请求：前端计算出的当前时间戳
     * @param offset 偏移量，用于跳过时间戳相同的博客记录 第一次请求：null offset = 0
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //查询当前用户收件箱
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FEED_KEY + userId;
        //查询时，按照得分(时间戳)范围查询，时间戳顺序为从大到小，代表新数据在前
        //不仅要查询数据，还要查询得分(时间戳)
        long count = 3L;
        Set<ZSetOperations.TypedTuple<String>> records = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, count);
        if (records == null || records.isEmpty()) {
            //收件箱为空
            return Result.ok();
        }
        //解析数据 blogIds, score(时间戳)->minTime(最小时间戳), offset(时间戳等于最小时间戳的记录条数)
        //records已经排好序了，按照score从大到小，不需要再转List排序 score: 5 4 4 2 2
        List<Long> blogIds = new ArrayList<>();
        long minTime = 0L;
        int curOffset = 1;
        for (ZSetOperations.TypedTuple<String> record : records) {
            blogIds.add(Long.parseLong(record.getValue()));
            if (record.getScore().longValue() == minTime) {
                curOffset++;
            } else {
                minTime = record.getScore().longValue();
                curOffset = 1;
            }
        }
        /*
        List<ZSetOperations.TypedTuple<String>> recordList = new ArrayList<>(records);
        //按照时间戳从小到大排列
        recordList.sort(new Comparator<ZSetOperations.TypedTuple<String>>() {
            @Override
            public int compare(ZSetOperations.TypedTuple<String> o1, ZSetOperations.TypedTuple<String> o2) {
                Double diff =  o1.getScore() - o2.getScore();
                if (diff  == 0) {
                    return 0;
                } else if (diff > 0) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        List<String> blogIds = new ArrayList<>();
        Long minTime = recordList.get(0).getScore().longValue();
        int curOffset = 0;
        for (ZSetOperations.TypedTuple<String> record : recordList) {
            blogIds.add(record.getValue());
            if (minTime.equals(record.getScore().longValue())) {
                curOffset++;
            }
        }
         */
        //根据blogIds查询blogs
        List<Blog> blogs = blogIds.stream()
                .map(blogId -> {
                    Blog blog = blogService.getById(blogId);
                    Long bloggerId = blog.getUserId();//发布者用户id
                    //根据用户id查询用户
                    User user = userService.getById(bloggerId);
                    //用户字段赋值，以便前端展示
                    blog.setIcon(user.getIcon());
                    blog.setName(user.getNickName());
                    //查询blog是否被当前用户点赞过(大拇指是否高亮)
                    blog.setIsLike(isBlogLiked(blog));
                    return blog;
                })
                .collect(Collectors.toList());
        //封装返回
        ScrollResult scrollResult = new ScrollResult(blogs, minTime, curOffset);
        return Result.ok(scrollResult);
    }
}
